package com.zengge.zbc.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.zengge.zbc.dto.Certificate;
import com.zengge.zbc.dto.Session;
import com.zengge.zbc.exception.ErrorCode;
import com.zengge.zbc.exception.ServiceException;
import com.zengge.zbc.mapper.UserMapper;
import com.zengge.zbc.po.UserInfo;
import com.zengge.zbc.service.LoginService;
import com.zengge.zbc.utils.JsonUtils;
import com.zengge.zbc.utils.SecretUtils;
import com.zengge.zbc.utils.http.HttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

@Service
public class LoginServiceImpl implements LoginService {

    private final static String APP_ID = "wx1b8c640efc52447f";
    private final static String APP_SECRET = "af45840244ef690247b5dfb0da0f7da2";
    private final static String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";
    private final HttpClient httpClient;
    private final UserMapper userMapper;

    @Autowired
    public LoginServiceImpl(HttpClient httpClient,
                            UserMapper userMapper) {
        this.httpClient = httpClient;
        this.userMapper = userMapper;
    }


    @Transactional
    @Override
    public String obtainToken(String code) throws Exception {

        String url = WX_LOGIN_URL + "?appid=" + APP_ID + "&secret=" + APP_SECRET + "&js_code=" + code + "&grant_type=authorization_code";
        Session session = httpClient.get(url, null, new TypeReference<Session>() {});
        if(session == null || session.getOpenid() == null || session.getSession_key() ==null)
            throw ServiceException.toError(ErrorCode.LOGIN_FAILED);

        UserInfo userInfo = userMapper.findUserInfoByUserId(session.getOpenid());
        if (userInfo == null) {
            userInfo = new UserInfo(session.getOpenid(), "", session.getSession_key());
            userMapper.save(userInfo);
        } else {
            userInfo.update(session.getSession_key());
            userMapper.update(userInfo);
        }
        Certificate certificate = new Certificate(String.valueOf(userInfo.getObjectId()), APP_ID);
        return SecretUtils.encrypt(JsonUtils.toJson(certificate));
    }
}
